﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
using ZYHand.Entity;
using ZYHand.Utility;
using Microsoft.Extensions.Configuration.Json;

namespace ZYHand.Repository
{
    public class RabbitMQClient
    {
        private static RabbitMQSetting rabbitMQSetting;//连接配置
        private static RabbitMQClient rabbitMQClient;//连接client对象
        private static ConnectionFactory connection;//连接对象

        //使用构造函数初始化配置
        public RabbitMQClient()
        {
            rabbitMQSetting = new RabbitMQSetting();
            rabbitMQSetting.HostName = AppSettingHelper.GetConfiguration().GetSection("RabbitMQ:HostName").Value;
            rabbitMQSetting.Port = Convert.ToInt32(AppSettingHelper.GetConfiguration().GetSection("RabbitMQ:Port").Value);
            rabbitMQSetting.UserName = AppSettingHelper.GetConfiguration().GetSection("RabbitMQ:UserName").Value;
            rabbitMQSetting.Password = AppSettingHelper.GetConfiguration().GetSection("RabbitMQ:Password").Value;
            rabbitMQSetting.VirtualHost = AppSettingHelper.GetConfiguration().GetSection("RabbitMQ:VirtualHost").Value;
        }

        //返回单例
        public static ConnectionFactory GetInstance()
        {
            if (rabbitMQClient == null)
            {
                rabbitMQClient= new RabbitMQClient();
            }
            return rabbitMQClient.GetConnectionFactory();
        }


        public ConnectionFactory GetConnectionFactory()
        {
            if (connection == null)
            {
                connection = new ConnectionFactory();
                connection.HostName = rabbitMQSetting.HostName;//主机名，Rabbit会拿这个IP生成一个endpoint，这个很熟悉吧，就是socket绑定的那个终结点。
                connection.Port = rabbitMQSetting.Port;
                connection.UserName = rabbitMQSetting.UserName;//默认用户名,用户可以在服务端自定义创建，有相关命令行
                connection.Password = rabbitMQSetting.Password;//默认密码
                connection.VirtualHost = rabbitMQSetting.VirtualHost;
            }
           
            return connection;
        }
    }
}
